
var connector = function (itemNavigation, carouselStage) {
    return carouselStage.jcarousel('items').eq(itemNavigation.index());
};

function initConnector() {
    var carouselStage = $('.carousel-stage').jcarousel();
    var carouselNavigation = $('.carousel-navigation').jcarousel();

    var mHeight = 600;
    var maxHeight = 0;
    carouselStage.jcarousel('items').each(function () {
        var item = $(this);
        if (maxHeight < item.height()) {
            maxHeight = item.height();
        }
    });
    if (maxHeight > mHeight) {
        maxHeight = mHeight;
    }
    $('.carousel-stage li').css({ "line-height": maxHeight - 3 + "px", "height": maxHeight + "px", width: "723.5px" });

    // We loop through the items of the navigation carousel and set it up
    // as a control for an item from the stage carousel.

    carouselNavigation.jcarousel('items').each(function () {
        var item = $(this);

        // This is where we actually connect to items.
        var target = connector(item, carouselStage);

        item
            .on('jcarouselcontrol:active', function () {
                carouselNavigation.jcarousel('scrollIntoView', this);
                item.addClass('active');
            })
            .on('jcarouselcontrol:inactive', function () {
                item.removeClass('active');
            })
            .jcarouselControl({
                target: target,
                carousel: carouselStage
            });
    });



    // Setup controls for the stage carousel
    $('.prev-stage')
        .on('jcarouselcontrol:inactive', function () {
            $(this).addClass('inactive');
        })
        .on('jcarouselcontrol:active', function () {
            $(this).removeClass('inactive');
        })
        .jcarouselControl({
            target: '-=1'
        });

    $('.next-stage')
        .on('jcarouselcontrol:inactive', function () {
            $(this).addClass('inactive');
        })
        .on('jcarouselcontrol:active', function () {
            $(this).removeClass('inactive');
        })
        .jcarouselControl({
            target: '+=1'
        });

    // Setup controls for the navigation carousel
    $('.prev-navigation')
        .on('jcarouselcontrol:inactive', function () {
            $(this).addClass('inactive');
        })
        .on('jcarouselcontrol:active', function () {
            $(this).removeClass('inactive');
        })
        .jcarouselControl({
            target: '-=1'
        });

    $('.next-navigation')
        .on('jcarouselcontrol:inactive', function () {
            $(this).addClass('inactive');
        })
        .on('jcarouselcontrol:active', function () {
            $(this).removeClass('inactive');
        })
        .jcarouselControl({
            target: '+=1'
        });
    carouselStage.jcarousel('scroll', 0);
    carouselNavigation.jcarousel('scroll', 0);
}


$(document).ready(function () { initConnector(); });